import { nextTick } from "../utils/next-tick";

const queue = []; // 存放 当前的 watcher
let has = {};
let pedding = false; // 防止开启多个 setTimeout

function flushSchedularQueue() {
  queue.forEach(watcher => watcher.run());
  queue.length = 0;
  has = {};
  pedding = false;
}

export function queueWatcher(watcher) {
  const id = watcher.id;
  // 对当前的 watcher 进行去重处理
  if (has[id] == null) {
    queue.push(watcher);
    has[id] = true;
    // 如果一个属性对应多个更新，那么就可能会开启多个 setTimeout。所以需要添加一个变量 pedding 来解决
    // setTimeout(() => {
    //   flushSchedularQueue()
    // }, 0)

    // 防止开启多个 setTimeout
    if (!pedding) {
      nextTick(flushSchedularQueue);
      pedding = true;
    }
  }
}
